package com.sinaapp.kltq.weathermanager;

import android.content.Context;

import com.sinaapp.kltq.data.WeatherData;
import com.sinaapp.kltq.data.WeatherDay;
import com.sinaapp.kltq.data.WeatherZhishu;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by 丰小兄 on 2015/7/16.
 * Function: XML解析层
 */
public class WeatherXML {
    public static boolean checkCity(String city, Context context) {
        // check network status
        if (!WeatherXML.checkNetwork(context)) {
            return false;
        }
        // check city existence
        try {
            // get source string
            URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi?city=" + URLEncoder.encode(city, "utf-8"));
            String source = WeatherNetwork.getStringFromURL(url, 3000);
            if (source == null) {
                return false;
            }
            // parse source string
            Document doc = DocumentHelper.parseText(source);
            Element root = doc.getRootElement();
            // check if the city valid
            if (root.element("error") != null) {
                return false;
            }
            return true;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }
    public static boolean checkNetwork(Context context) {
        // check network connected
        if (!WeatherNetwork.checkNetwork(context)) {
            return false;
        }
        // check access to weather data
        try {
            // get source string
            URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi?city=" + URLEncoder.encode("北京", "utf-8"));
            String source = WeatherNetwork.getStringFromURL(url, 3000);
            if (source == null) {
                return false;
            }
            // parse source string
            Document doc = DocumentHelper.parseText(source);
            Element root = doc.getRootElement();
            // check if the data right
            return (root != null && root.element("city") != null);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return false;
        }
    }
    // if get nothing, return null
    public static WeatherData getWeatherDataByHttp(URL url, int timeout) {
        String source = WeatherNetwork.getStringFromURL(url, timeout);
        if (source == null) {
            return null;
        }
        // parse source string
        Document doc;
        try {
            WeatherData data = new WeatherData();
            doc = DocumentHelper.parseText(source);
            Element root = doc.getRootElement();
            Element tempNode;
            // set extra info
            data.date = new Date(System.currentTimeMillis());
            if ((tempNode = root.element("error")) != null) {
                data.error = tempNode.getText();
            }
            // parse realtime data
            if ((tempNode = root.element("city")) != null) {
                data.realTime.city = tempNode.getText();
            }
            if ((tempNode = root.element("updatetime")) != null) {
                data.realTime.updateTime = tempNode.getText();
            }
            if ((tempNode = root.element("wendu")) != null) {
                data.realTime.wendu = Integer.parseInt(tempNode.getText());
            }
            if ((tempNode = root.element("fengli")) != null) {
                data.realTime.fengli = tempNode.getText();
            }
            if ((tempNode = root.element("shidu")) != null) {
                data.realTime.shidu = tempNode.getText();
            }
            if ((tempNode = root.element("fengxiang")) != null) {
                data.realTime.fengxiang = tempNode.getText();
            }
            if ((tempNode = root.element("sunrise_1")) != null) {
                data.realTime.sunrise_1 = tempNode.getText();
            }
            if ((tempNode = root.element("sunset_1")) != null) {
                data.realTime.sunset_1 = tempNode.getText();
            }
            if ((tempNode = root.element("sunrise_2")) != null) {
                data.realTime.sunrise_2 = tempNode.getText();
            }
            if ((tempNode = root.element("sunset_2")) != null) {
                data.realTime.sunset_2 = tempNode.getText();
            }
            // parse environment data
            if (root.element("environment") != null) {
                if ((tempNode = root.element("environment").element("aqi")) != null) {
                    data.environment.aqi = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("pm25")) != null) {
                    data.environment.pm25 = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("suggest")) != null) {
                    data.environment.suggest = tempNode.getText();
                }
                if ((tempNode = root.element("environment").element("quality")) != null) {
                    data.environment.quality = tempNode.getText();
                }
                if ((tempNode = root.element("environment").element("MajorPollutants")) != null) {
                    data.environment.MajorPollutants = tempNode.getText();
                }
                if ((tempNode = root.element("environment").element("o3")) != null) {
                    data.environment.o3 = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("co")) != null) {
                    data.environment.co = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("pm10")) != null) {
                    data.environment.pm10 = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("so2")) != null) {
                    data.environment.so2 = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("no2")) != null) {
                    data.environment.no2 = Integer.parseInt(tempNode.getText());
                }
                if ((tempNode = root.element("environment").element("time")) != null) {
                    data.environment.time = tempNode.getText();
                }
            }
            // parse alarm data
            if (root.element("alarm") != null) {
                if ((tempNode = root.element("alarm").element("cityKey")) != null) {
                    data.alarm.cityKey = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("cityName")) != null) {
                    data.alarm.cityName = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("alarmType")) != null) {
                    data.alarm.alarmType = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("alarmDegree")) != null) {
                    data.alarm.alarmDegree = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("alarmText")) != null) {
                    data.alarm.alarmText = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("alarm_details")) != null) {
                    data.alarm.alarmDetails = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("standard")) != null) {
                    data.alarm.standard = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("suggest")) != null) {
                    data.alarm.suggest = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("imgURL")) != null) {
                    data.alarm.imgURL = tempNode.getText();
                }
                if ((tempNode = root.element("alarm").element("time")) != null) {
                    data.alarm.time = tempNode.getText();
                }
            } else {
                data.alarm.alarmType = "none";
            }
            // parse yesterday data
            if (root.element("yesterday") != null) {
                if ((tempNode = root.element("yesterday").element("date_1")) != null) {
                    int month = new Date(System.currentTimeMillis()).getMonth() + 1;    // 获得月份
                    int dayNum = new Date(System.currentTimeMillis()).getDate();
                    // 如果是月初
                    if (dayNum == 1) {
                        month --;
                        // 如果是年初
                        if (month == 0) {
                            month = 12;
                        }
                    }
                    data.yesterday.date = String.format("%02d", month) + tempNode.getText();
                }
                if ((tempNode = root.element("yesterday").element("high_1")) != null) {
                    data.yesterday.high = tempNode.getText();
                }
                if ((tempNode = root.element("yesterday").element("low_1")) != null) {
                    data.yesterday.low = tempNode.getText();
                }
                if (root.element("yesterday").element("day_1") != null) {
                    if ((tempNode = root.element("yesterday").element("day_1").element("type_1")) != null) {
                        data.yesterday.dayType = tempNode.getText();
                    }
                    if ((tempNode = root.element("yesterday").element("day_1").element("fx_1")) != null) {
                        data.yesterday.dayFx = tempNode.getText();
                    }
                    if ((tempNode = root.element("yesterday").element("day_1").element("fl_1")) != null) {
                        data.yesterday.dayFl = tempNode.getText();
                    }
                }
                if (root.element("yesterday").element("night_1") != null) {
                    if ((tempNode = root.element("yesterday").element("night_1").element("type_1")) != null) {
                        data.yesterday.nightType = tempNode.getText();
                    }
                    if ((tempNode = root.element("yesterday").element("night_1").element("fx_1")) != null) {
                        data.yesterday.nightFx = tempNode.getText();
                    }
                    if ((tempNode = root.element("yesterday").element("night_1").element("fl_1")) != null) {
                        data.yesterday.nightFl = tempNode.getText();
                    }
                }
            }
            // parse forecast data
            if ((tempNode = root.element("forecast")) != null) {
                List<Element> elements = tempNode.elements("weather");
                if (elements != null) {
                    for (int i = 0; i < elements.size(); i ++) {
                        WeatherDay day = new WeatherDay();
                        if ((tempNode = elements.get(i).element("date")) != null) {
                            day.date = tempNode.getText();
                            // 如果日>月长度-4则遇1234月份加1
                            int monthLength = 0;
                            String monthStr = "";
                            switch (new Date(System.currentTimeMillis()).getMonth() + 1) {
                                case 1:
                                    monthLength = 31;
                                    monthStr = "02";
                                    break;
                                case 3:
                                    monthLength = 31;
                                    monthStr = "04";
                                    break;
                                case 5:
                                    monthLength = 31;
                                    monthStr = "06";
                                    break;
                                case 7:
                                    monthLength = 31;
                                    monthStr = "08";
                                    break;
                                case 8:
                                    monthLength = 31;
                                    monthStr = "09";
                                    break;
                                case 10:
                                    monthLength = 31;
                                    monthStr = "11";
                                    break;
                                case 12:
                                    monthLength = 31;
                                    monthStr = "01";
                                    break;
                                case 4:
                                    monthLength = 30;
                                    monthStr = "05";
                                    break;
                                case 6:
                                    monthLength = 30;
                                    monthStr = "07";
                                    break;
                                case 9:
                                    monthLength = 30;
                                    monthStr = "10";
                                    break;
                                case 11:
                                    monthLength = 30;
                                    monthStr = "11";
                                    break;
                                case 2:
                                    int year = new Date(System.currentTimeMillis()).getYear() + 1900;
                                    if (year % 400 == 0) {     // 如果是闰年
                                        monthLength = 29;
                                    } else if (year % 100 != 0 && year % 4 == 0) {
                                        monthLength = 29;
                                    } else {    // 如果不是
                                        monthLength = 28;
                                    }
                                    monthStr = "03";
                                    break;
                            }
                            int dayNum = (Integer.parseInt(day.date.substring(0, day.date.length() - 4)));
                            if (new Date(System.currentTimeMillis()).getDate() > monthLength - 4 && dayNum > 0 && dayNum < 5) {
                                if (day.date.substring(1, 2).compareTo("日") == 0) {
                                    day.date = monthStr + "0" + tempNode.getText();
                                } else {
                                    day.date = monthStr + tempNode.getText();
                                }
                            } else {
                                if (day.date.substring(1, 2).compareTo("日") == 0) {
                                    day.date = new SimpleDateFormat("MM").format(new Date(System.currentTimeMillis())) + "0" + tempNode.getText();
                                } else {
                                    day.date = new SimpleDateFormat("MM").format(new Date(System.currentTimeMillis())) + tempNode.getText();
                                }
                            }
                        }
                        if ((tempNode = elements.get(i).element("high")) != null) {
                            day.high = tempNode.getText();
                        }
                        if ((tempNode = elements.get(i).element("low")) != null) {
                            day.low = tempNode.getText();
                        }
                        if (elements.get(i).element("day") != null) {
                            if ((tempNode = elements.get(i).element("day").element("type")) != null) {
                                day.dayType = tempNode.getText();
                            }
                            if ((tempNode = elements.get(i).element("day").element("fengxiang")) != null) {
                                day.dayFx = tempNode.getText();
                            }
                            if ((tempNode = elements.get(i).element("day").element("fengli")) != null) {
                                day.dayFl = tempNode.getText();
                            }
                        }
                        if (elements.get(i).element("night") != null) {
                            if ((tempNode = elements.get(i).element("night").element("type")) != null) {
                                day.nightType = tempNode.getText();
                            }
                            if ((tempNode = elements.get(i).element("night").element("fengxiang")) != null) {
                                day.nightFx = tempNode.getText();
                            }
                            if ((tempNode = elements.get(i).element("night").element("fengli")) != null) {
                                day.nightFl = tempNode.getText();
                            }
                        }
                        data.forecast.add(day);
                    }
                }
            }
            // parse 指数
            if ((tempNode = root.element("zhishus")) != null) {
                List<Element> elements = tempNode.elements("zhishu");
                if (elements != null) {
                    for (int i = 0; i < elements.size(); i++) {
                        WeatherZhishu zhishu = new WeatherZhishu();
                        if ((tempNode = elements.get(i).element("name")) != null) {
                            zhishu.name = tempNode.getText();
                        }
                        if ((tempNode = elements.get(i).element("value")) != null) {
                            zhishu.value = tempNode.getText();
                        }
                        if ((tempNode = elements.get(i).element("detail")) != null) {
                            zhishu.detail = tempNode.getText();
                        }
                        data.zhishus.add(zhishu);
                    }
                }
            }
            return data;
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }
}
